import axios from "axios";
import { showToast } from "vant";
import router from "../router";

// 创建axios实例
const service = axios.create({
  baseURL: "http://localhost:3000/api",
  timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data.success) {
      return data;
    } else {
      showToast(data.message || "操作失败");
      return Promise.reject(data);
    }
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        localStorage.removeItem("token");
        router.push("/login");
        showToast("登录已过期，请重新登录");
      } else {
        showToast(error.response.data?.message || "网络错误");
      }
    } else {
      showToast("网络连接失败");
    }
    return Promise.reject(error);
  }
);

export default service;
